<?php namespace App\Http\Controllers\Api;

use App\Goods;
use App\Http\Controllers\Controller;
use App\Orders;
use App\User;
use Illuminate\Contracts\Auth\Guard;
use Illuminate\Http\Request;
use EasyWeChat\Payment\Order;
use Log;

class PaymentController extends Controller
{
    public function payByWechatJsApi(Guard $guard,Request $request){
        $orderNum = $request->get('order_num');

        if($guard->guest())
            return response()->json(['level'=>'error','message'=>'请先登录']);

        /** @var User $user */
        $user = $guard->user();

        /** @var Orders $thatOrder */
        $thatOrder = Orders::whereOrderNum($orderNum)->first();
        if(!$thatOrder)
            return response()->json(['level'=>'error','message'=>'当前订单不存在']);

        $title = '';
        /** @var Goods $thatGood */
        $thatGood = Goods::whereId($thatOrder->good_id)->first();
        if($thatGood){
            $title = $thatGood->name;
        }

        $openId = $user->wechat_openid;
        $app = app("wechat");
        $attributes = [
            'trade_type'       => 'JSAPI',
            'body'             => '商品费用',
            'detail'           => $title.'购买费用',
            'out_trade_no'     => $thatOrder->order_num,
            'total_fee'        => (float)$thatOrder->amount * 100,
            'notify_url'       => route('Api.Payment.wechatPayCallBack'),
            'openid'           => $openId,
        ];
        $payment = $app->payment;
        $order = new Order($attributes);
        $result = $payment->prepare($order);
        if ($result->return_code == 'SUCCESS' && $result->result_code == 'SUCCESS'){
            $prepayId = $result->prepay_id;
            $json = $payment->configForPayment($prepayId);
            return response()->json(['level'=>'success','message'=>trans('获取支付信息成功'),'data'=>json_decode($json)]);
        }else{
            return response()->json(['level'=>'error','message'=>'创建支付信息失败','data'=>$result]);
        }
    }

    public function wechatPayCallBack(){
        $app = app("wechat");

        $response = $app->payment->handleNotify(function($notify, $successful){
            Log::info('order_num=>'.$notify->out_trade_no);

            /** @var Orders $thatOrder */
            $thatOrder= Orders::whereOrderNum($notify->out_trade_no)->first();
            if (!$thatOrder) {
                return 'Order not exist.';
            }

            if ($thatOrder->is_pay == 1) {
                return true;
            }

            if ($successful) {
                $thatOrder->pay_time = date('Y-m-d H:i:s',time());
                $thatOrder->is_pay   = 1;
                $thatOrder->status   = 1;
                $thatOrder->save();

                $thatGoods = Goods::whereId($thatOrder->good_id)->first();
                if($thatGoods){
                    $lastStock = (int)$thatGoods->stock - (int)$thatOrder->num;
                    if($lastStock < 0)$lastStock = 1;
                    $thatGoods->stock = $lastStock;
                    $thatGoods->save();
                }

                return true;
            } else {
                $thatOrder->is_pay = 0;
                $thatOrder->save();

                return 'fail.';
            }



        });

        return $response;
    }
}